package bank_controller

import (
	"fmt"
	"net/http"
	"transaction-demo/db"
	"transaction-demo/entity"

	"github.com/gin-gonic/gin"
)

func BankTrade(c *gin.Context) {
	// 完成张三的balance+100，李四的balance-100操作，需要事务
	tx := db.DB.Begin()
	// 一旦发生错误，就回滚
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": "发生异常，交易失败",
				"success": false,
			})
		}
	}()
	var sqlStr string
	// 张三扣100元
	sqlStr = "update tb_bank set balance = balance - 100 where username = '张三'"
	fmt.Println(sqlStr)
	result1 := tx.Exec(sqlStr)
	if result1.Error != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "张三的余额不足，交易失败",
			"success": false,
		})
		return
	}
	// panic("panic")
	// 李四增100元
	sqlStr = "update tb_bank set balance = balance + 100 where username = '李四'"
	fmt.Println(sqlStr)
	result2 := tx.Exec(sqlStr)
	if result2.Error != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "李四账户增加100元失败，请重试",
			"success": false,
		})
		return
	}
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "交易成功！",
		"success": true,
	})
}

func GetBankRecord(c *gin.Context) {
	bankRecordList := []entity.Bank{}
	db.DB.Find(&bankRecordList)
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "Get Bank Record Successfully!",
		"success": true,
		"data":    bankRecordList,
	})
}

func UpdateBand(c *gin.Context) {
	result := db.DB.Exec("update tb_bank set balance = balance + 100 where username = '张三'")
	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "Update Bank Failed!",
			"success": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "Update Bank Successfully!",
		"success": true,
	})
}
